<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">领新编号：</label>
                                    <div class="layui-input-inline">
                                        <input name="code" class="layui-input" type="text" placeholder="领新编号" autocomplete="off"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">工单编号：</label>
                                    <div class="layui-input-inline">
                                        <input name="workOrderCode" class="layui-input" type="text" placeholder="工单编号" autocomplete="off"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">柜子编号：</label>
                                    <div class="layui-input-inline">
                                        <input name="cabinetCode" class="layui-input" type="text" placeholder="柜子编号"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">申请时间：</label>
                                    <div class="layui-input-inline">
                                        <input id="pTime" class="layui-input" type="text" placeholder="选择创建时间"
                                               autocomplete="off" readonly/>
                                        <input name="startCreateTime" id="sTime" style="display: none"/>
                                        <input name="endCreateTime" id="eTime" style="display: none"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">审核状态：</label>
                                    <div class="layui-input-inline">
                                        <select name="checkStatus" class="common-select-search">
                                            <option value="">审核状态</option>
                                            <option value="approve">审核通过</option>
                                            <option value="reject">驳回待审核</option>
                                            <option value="toaudit">待审核</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">订单状态：</label>
                                    <div class="layui-input-inline">
                                        <select name="status" class="common-select-search">
                                            <option value="">订单状态</option>
                                            <option value="toaudit">待审核</option>
                                            <option value="toreceive">待领取</option>
                                            <option value="checked">已审核</option>
                                            <option value="portion">部分领取</option>
                                            <option value="broughtout">已领完</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog"
                                            lay-submit layui-form-keyDownSearch="true">查询
                                    </button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button type="button" id="storesRequisitionBtnAdd" class="layui-btn icon-btn color-reseda">
                                添加领新申请
                            </button>
                        </div>
                        <div class="lay-btn-rt">
                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="storesRequisitionTable" lay-filter="storesRequisitionTable"></table>
        </div>
    </div>
</div>

<style>
    /*div[lay-id="storesRequisitionAddProductTable"] .layui-form,*/
    /*div[lay-id="storesRequisitionAddProductTable"] .layui-table-box,*/
    /*div[lay-id="storesRequisitionAddProductTable"] .layui-table-body,*/
    /*div[lay-id="storesRequisitionAddProductTable"] .layui-table-cell {*/
        /*overflow: visible;*/
    /*}*/
</style>

<!-- 表格操作列 -->
<script type="text/html" id="storesRequisitionTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">详情</a>
    {{# if(d.status == "toaudit"){  }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="check">审核</a>
    {{# }else if((d.status == "checked" || d.status == "portion") && d.checkStatus == "approve"){ }}
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="send">发送短信通知</a>
    {{# } }}
</script>

<!--发送短信通知-->
<script type="text/html" id="storesRequisitionTopTableBar">
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="send">发送短信通知</a>
</script>

<!--添加物料操作按钮-->
<script type="text/html" id="storesRequisitionAddProductTableBar">
    {{# if(d.status == "no"){  }}
    <a class="layui-btn layui-btn-xs" lay-event="save">保存</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    {{# }else if(d.status =="yes"){ }}
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</a>
    {{# } }}
</script>

<!-- 添加领新申请 -->
<script type="text/html" id="storesRequisitionAddTemplate">
    <form lay-filter="storesRequisitionAddForm" class="layui-form model-form form-scroll storesRequisitionAddForm">
        <div class="open-details-box pd-20">
            <div class="custom-table" style="padding-top: 20px;">
                <ul class="t-header page-flex">
                    <li>出货货柜</li>
                    <!--<li>所属工序</li>
                    <li>所属开工单</li>-->
                    <li>选择领取人</li>
                    <li>领取人电话</li>
                    <li>所属部门</li>
                    <li>所属岗位</li>
                </ul>
                <div class="t-body page-flex">
                    <div class="cell">
                        <select name="cabinetId" id="cabinetId" lay-filter="cabinetId"
                                lay-verify="required">
                            <option value="">选择智能柜</option>
                        </select>
                    </div>
                    <!--<div class="cell" id="selectProcessId">
                        <input name="processId" class="layui-input" type="text" placeholder="选择工序" lay-verify="required"
                               disabled style="cursor: pointer;color: #333;"/>
                    </div>
                    <div class="cell" id="selectWorkOrderId">
                        <input name="workOrderId" class="layui-input" type="text" placeholder="选择开工单"
                               disabled style="cursor: pointer;color: #333;"/>
                    </div>-->
                    <div class="cell">
                        <select name="userId" id="userId" lay-filter="userId"
                                lay-verify="required">
                        </select>
                    </div>
                    <div class="cell">
                        <span class="phone"></span>
                    </div>
                    <div class="cell">
                        <span class="departmentName"></span>
                    </div>
                    <div class="cell">
                        <span class="roleName"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item table-bor table-ht-auto msg-none">
                <div class="layui-form-item" style="margin: 20px 0 10px;">
                    <div class="open-details-title">领新物料</div>
                </div>
                <table class="layui-table" id="storesRequisitionAddProductTable"
                       lay-filter="storesRequisitionAddProductTable"></table>
                <button class="layui-btn addTable storesRequisitionAddProductBtn" type="button">添加物料</button>
            </div>
        </div>
        <div class="layui-form-item text-right pd-20">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="storesRequisitionAddFormSubmit" lay-submit>提交</button>
        </div>
    </form>
</script>

<!--选择工序-->
<script type="text/html" id="selectProcessListAdd">
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body">
                <!-- 头部操作栏 -->
                <div class="layui-form toolbar">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label w-auto">工序编号：</label>
                            <div class="layui-input-inline mr0" style="width: 240px;">
                                <input name="code" class="layui-input" type="text" placeholder="工序编号"/>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button class="layui-btn icon-btn" lay-filter="selectStorageSignListAddFormSubSearchLog"
                                    lay-submit style="padding: 0 24px;" layui-form-keyDownSearch="true">搜索
                            </button>
                            <button id="selectStorageSignListAddClose" class="layui-btn icon-btn">确认选择</button>
                        </div>
                    </div>
                </div>

                <!-- 表格 -->
                <table class="layui-table" id="selectStorageSignListAddTable"
                       lay-filter="selectStorageSignListAddTable"></table>
            </div>
        </div>
    </div>
</script>

<!--选择开工单-->
<script type="text/html" id="selectTheWorkProcessTemplate">
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body">
                <!-- 头部操作栏 -->
                <div class="layui-form toolbar">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label w-auto">开工单编号：</label>
                            <div class="layui-input-inline mr0" style="width: 240px;">
                                <input name="code" class="layui-input" type="text" placeholder="开工单编号"/>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button class="layui-btn icon-btn" lay-filter="selectTheWorkProcessFormSubSearchLog"
                                    lay-submit style="padding: 0 24px;">
                                搜索
                            </button>
                            <button id="selectTheWorkProcessClose" class="layui-btn icon-btn">确认选择</button>
                        </div>
                    </div>
                </div>
                <!-- 表格 -->
                <table class="layui-table" id="selectTheWorkProcessTable"
                       lay-filter="selectTheWorkProcessTable"></table>
            </div>
        </div>
    </div>
</script>

<!--添加物料弹窗-->
<script type="text/html" id="selectProductStockTemplate">
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body">
                <!-- 头部操作栏 -->
                <div class="layui-form toolbar">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label w-auto">物料编号：</label>
                            <div class="layui-input-inline mr0" style="width: 240px;">
                                <input name="skuCode" class="layui-input" type="text" placeholder="物料编号"/>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button class="layui-btn icon-btn" lay-filter="selectProductStockFormSubSearchLog" layui-form-keyDownSearch="true"
                                    lay-submit style="padding: 0 24px;">
                                搜索
                            </button>
                            <button id="selectProductStockClose" class="layui-btn icon-btn">确认选择</button>
                        </div>
                    </div>
                </div>
                <!-- 表格 -->
                <div class="table-ht-auto scroll-table-5">
                    <table class="layui-table" id="selectProductStockTable"
                           lay-filter="selectProductStockTable"></table>
                </div>
            </div>
        </div>
    </div>
</script>

<!--详情弹窗-->
<script type="text/html" id="storesRequisitionDetailTemplate">
    <form lay-filter="storesRequisitionDetailTemplate" class="layui-form model-form form-scroll">
        <div class="open-details-box pd-20 table-bor">
            <table class="layui-table" id="storesRequisitionTopTable"
                   lay-filter="storesRequisitionTopTable"></table>
            <div class="layui-form-item" style="margin: 20px 0 10px;">
                <div class="open-details-title">领新物料</div>
            </div>
            <table class="layui-table" id="storesRequisitionBottomTable"
                   lay-filter="storesRequisitionBottomTable"></table>
            <div class="layui-form-item" style="margin-top: 20px;">
                <label class="layui-form-label w-auto">审核状态：</label>
                <div class="layui-input-inline">
                    <select name="checkStatus" id="checkStatus" lay-filter="checkStatus"
                            lay-verify="required">
                        <option value="">请选择</option>
                        <option value="approve">审核通过</option>
                        <option value="reject">审核驳回</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-form-item text-right pd-20">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn isCheckStatus" lay-filter="storesRequisitionDetailFormSubmit" lay-submit>提交
            </button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin', 'laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var laydate = layui.laydate;

        form.render('select');
        admin.selectSearch();

        //时间范围
        laydate.render({
            elem: '#pTime',
            type: 'date',
            range: true,
            done: function (value, date, endDate) {
                if (value) {
                    let dateValue = value.split(" - ");
                    $("input[name='startCreateTime']").val(dateValue[0] + " 00:00:00");
                    $("input[name='endCreateTime']").val(dateValue[1] + " 23:59:59");
                } else {
                    $("input[name='startCreateTime']").val("");
                    $("input[name='endCreateTime']").val("");
                }
                setTimeout(function() {$('[lay-filter="formSubSearchLog"]').click()}, 300);
            }
        });

        // 渲染表格
        var insTb = table.render({
            elem: '#storesRequisitionTable',
            url: config.base + 'enterprisecab/cabinet/admin/storesRequisition/list',
            toolbar: true,
            defaultToolbar: ["filter"],
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers', title: '序号', fixed: 'left'}
                ,{field: 'code', title: '领新编号', fixed: 'left', width: 160}
                , {field: 'cabinetCode', title: '柜子编号', fixed: 'left', width: 190}
                , {field: 'productQuantity', title: '物料数量'}
                , {field: 'totalPrices', title: '货值'}
                , {field: 'workOrderCode', title: '所属工单信息', width: 120,templet:d  => d.workOrderCode?d.workOrderCode:'无'}
                , {field: 'deviceCode', title: '机台信息', templet: function (d) {
                    return d.deviceCode ? d.deviceCode : "无"
                }}
                ,{field: 'packName', title: '包装规格', templet: function (d) {
                        return d.packName ? d.packName : "无"
                    }}
                ,{field: 'shipmentQuantity', title: '包装数量', templet: function (d) {
                        return d.shipmentQuantity ? Math.abs(d.shipmentQuantity) : "无"
                    }}
                ,{field: 'unitName', title: '包装单位', templet: function (d) {
                        return d.unitName ? d.unitName : "无"
                    }}
                ,{field: 'quantityPack', title: '基础数量', templet: function (d) {
                        return d.quantityPack ? Math.abs(d.quantityPack) : "无"
                    }}
                ,{field: 'basicsUnitName', title: '基础单位', templet: function (d) {
                        return d.basicsUnitName ? d.basicsUnitName : "无"
                    }}
                , {field: 'creatorName', sort: true,title: '申请人'}
                , {field: 'createTime', sort: true,title: '申请时间', width: 160}
                , {field: 'auditPerson', sort: true,title: '审核人'}
                , {field: 'checkStatusDesc', title: '审核状态'}
                , {field: 'statusDesc', title: '订单状态'}
                , {toolbar: '#storesRequisitionTableBar', title: '操作', width: 200, fixed: 'right'}
            ]],
        });

        // 工具条点击事件
        table.on('tool(storesRequisitionTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'detail') { // 详情
                storesRequisitionDetailModel(data, 'detail');
            } else if (obj.event === 'check') { // 审核
                storesRequisitionDetailModel(data, 'check');
            } else if (obj.event === 'send') {
                storesRequisitionDetailModel(data, 'send');
            }
        });

        //监听排序
        table.on('sort(storesRequisitionTable)', function (obj) {
            table.reload('storesRequisitionTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        form.on('submit(resets)', function (data) {
            $(".lay-header").find('select').val("");
            $(".lay-header").find('input').val("");
            var field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
        });

        // 添加按钮点击事件
        $('#storesRequisitionBtnAdd').click(function () {
            storesRequisitionAddModel();
        });

        // 显示编辑弹窗
        function storesRequisitionAddModel() {
            admin.open({
                type: 1,
                area: ['82%', '840px'],
                offset: '65px',
                title: '添加领新申请',
                content: $('#storesRequisitionAddTemplate').html(),
                success: function () {
                    // 工序ID && 工单ID
                    let processId = '', workOrderId = '', cabinetId = '', cabinetCode = '';
                    let productList = [];
                    let workOrderWay = ''; // 用于判断工单请求接口
                    let packData = [];
                    admin.req('enterprise/system/admin/systemRuleInfo/getSystemRuleInfo', {}, res => {
                        if (res.code === 200) {
                            workOrderWay = res.data.workOrderWay;
                        }
                    }, 'get');
                    admin.reqSync('enterprise/product/admin/productPack/list', {page: 1, limit: 99999}, res => {
                        if (res.code === 200) {
                            packData = res.data
                        } else {
                            packData = [];
                        }
                    }, 'get');

                    // 获取出货货柜
                    admin.req('enterprisecab/cabinet/admin/cabinet/getCabinetAll', {
                        cabinetNature: 'main'
                    }, function (res) {
                        if (res.code == 200) {
                            loadSelectHtml(res.data, "选择智能柜", "cabinetId", 1);
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }, 'GET');
                    // 选择柜子
                    form.on("select(cabinetId)", function (d) {
                        let elem = d.elem;
                        cabinetId = elem[elem.selectedIndex].value;
                        cabinetCode = elem[elem.selectedIndex].text;
                    });

                    // 获取领取人
                    admin.req('user/admin/user/getAll', {
                        cabinetNature: 'sale'
                    }, function (res) {
                        if (res.code == 200) {
                            loadSelectHtml(res.data, "选择领取人", "userId", 2);
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }, 'GET');

                    // 选择领取人
                    form.on("select(userId)", function (d) {
                        let elem = d.elem;
                        let id = elem[elem.selectedIndex].value;
                        getUserInfoByUserId(id);
                    });

                    // 获取领取人信息
                    function getUserInfoByUserId(id) {
                        admin.req('user/admin/user/getUserInfoByUserId', {
                            userId: id
                        }, function (res) {
                            if (res.code == 200) {
                                $(".phone").text(res.data.phone);
                                $(".departmentName").text(res.data.departmentName);
                                $(".roleName").text(res.data.roleName);
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'GET');
                    }

                    // 选择工序
                    $("#selectProcessId").click(function () {
                        alert(1);
                        var processInfoList = admin.open({
                            type: 1,
                            title: '选择工序',
                            area: '75%',
                            offset: '120px',
                            content: $('#selectProcessListAdd').html(),
                            success: function () {
                                form.render("select");

                                // 渲染表格
                                var selectStorageSignListAddTable = table.render({
                                    elem: '#selectStorageSignListAddTable',
                                    url: config.base + 'production/productionPlan/admin/productionPlan/getProcessInfoPageList',
                                    page: true,
                                    cellMinWidth: 100,
                                    cols: [[
                                        {type: 'radio'}
                                        , {field: 'nodeCodes', title: '工序编号'}
                                        , {field: 'nodeNames', title: '工序名称'}
                                        , {field: 'creatorName', title: '创建人'}
                                        , {field: 'createTime', title: '创建时间'}
                                    ]],
                                });

                                // 搜索
                                form.on('submit(selectStorageSignListAddFormSubSearchLog)', function (data) {
                                    selectStorageSignListAddTable.reload({where: data.field, page: {curr: 1}}, 'data');
                                });

                                // 确认选择
                                $('#selectStorageSignListAddClose').click(function () {
                                    let checkStatus = table.checkStatus('selectStorageSignListAddTable'); //test即为基础参数id对应的值
                                    let dataS = checkStatus.data;
                                    if (checkStatus.data.length == 0) {
                                        layer.msg("请选择工序", {icon: 2, time: 1000});
                                    } else {
                                        processId = dataS[0].id;
                                        $("input[name='processId']").val(dataS[0].nodeNames);
                                        layer.close(processInfoList);
                                    }
                                });
                            }
                        })
                    });

                    // 所属开工单
                    $("#selectWorkOrderId").click(function () {
                        if (processId == '') {
                            layer.msg("请先选择工序", {icon: 2});
                            return false;
                        }
                        if (workOrderWay == '') {
                            layer.msg("数据错误,请联系管理员", {icon: 2});
                            return false;
                        }
                        let url = 'production/productionPlan/admin/productionWorkOrder/list?processId=' + processId; //请求工单地址
                        let selectTheWorkProcessTemplateCols = [[
                            {type: 'radio'}
                            , {field: 'code', title: '工单编码', width: '160'}
                            , {field: 'processName', title: '所属工序'}
                            , {field: 'planCode', title: '所属生产计划'}
                            , {field: 'workOrderQualityDesc', title: '工单性质'}
                            , {field: 'deviceCode', title: '责任工站'}
                            , {field: 'skuCode', title: '物料编码'}
                            , {field: 'productionQuantity', title: '排产数量'}
                            , {field: 'finishQuantity', title: '已经完成'}
                            // , {field: 'predictStartTime', title: '预计开始时间'}
                            // , {field: 'predictFinishTime', title: '预计完工时间'}
                            , {field: 'statusDesc', title: '状态'}
                        ]] // 列表头
                        if (workOrderWay == 'mes') {
                            url = 'production/productionPlan/admin/productionWorkOrder/list?processId=' + processId;
                            selectTheWorkProcessTemplateCols = [[
                                {type: 'radio'}
                                , {field: 'code', title: '工单编码', width: '160'}
                                , {field: 'processName', title: '所属工序'}
                                , {field: 'planCode', title: '所属生产计划'}
                                , {field: 'workOrderQualityDesc', title: '工单性质'}
                                , {field: 'deviceCode', title: '责任工站'}
                                , {field: 'skuCode', title: '物料编码'}
                                , {field: 'productionQuantity', title: '排产数量'}
                                , {field: 'finishQuantity', title: '已经完成'}
                                // , {field: 'predictStartTime', title: '预计开始时间'}
                                // , {field: 'predictFinishTime', title: '预计完工时间'}
                                , {field: 'statusDesc', title: '状态'}
                            ]]
                        } else if (workOrderWay == 'simple') {
                            url = 'production/productionPlan/admin/simpleWorkOrder/list?processId=' + processId;
                            selectTheWorkProcessTemplateCols = [[
                                {type: 'radio'}
                                , {field: 'code', title: '工单编码', width: '300'}
                                , {field: 'processName', title: '所属工序', width: '300'}
                                , {field: 'skuCode', title: '物料编码', width: '300'}
                                , {field: 'productionQuantity', title: '排产数量', width: '300'}
                            ]]
                        }
                        var selectTheWorkProcessTemplate = admin.open({
                            type: 1,
                            title: '选择开工单',
                            area: '75%',
                            offset: '120px',
                            content: $('#selectTheWorkProcessTemplate').html(),
                            success: function () {
                                form.render("select");
                                // 渲染表格
                                var selectTheWorkProcessTable = table.render({
                                    elem: '#selectTheWorkProcessTable',
                                    url: config.base + url,
                                    page: true,
                                    cellMinWidth: 100,
                                    cols: selectTheWorkProcessTemplateCols,
                                    parseData: function (res, curr, count) {
                                        /*let resArr = [];
                                        resArr = res.data.filter((item) => !productList.some((ele) => ele.skuCode === item.skuCode))
                                        res.data = resArr;
                                        return res*/
                                    }
                                });

                                // 搜索
                                form.on('submit(selectTheWorkProcessFormSubSearchLog)', function (data) {
                                    selectTheWorkProcessTable.reload({
                                        where: data.field,
                                        page: {curr: 1}
                                    }, 'data');
                                });

                                // 确认选择
                                $('#selectTheWorkProcessClose').click(function () {
                                    let checkStatus = table.checkStatus('selectTheWorkProcessTable'); //test即为基础参数id对应的值
                                    let dataS = checkStatus.data[0];
                                    if (checkStatus.data.length == 0) {
                                        layer.msg("请选择开工单", {icon: 2, time: 1000});
                                    } else {

                                        let filterList = productList.filter((item) => {
                                            return item.skuCode == dataS.skuCode
                                        });
                                        if (filterList.length > 0) {
                                            layer.msg('当前选择的物料已存在', {icon: 2});
                                            return false;
                                        }

                                        workOrderId = dataS.id;
                                        $("input[name='workOrderId']").val(dataS.code);

                                        admin.reqSync('enterprise/product/admin/productDetail/getProductDetailBySkuCode', {skuCode: dataS.skuCode}, res => {
                                            if (res.code === 200) {
                                                if (Object.prototype.isPrototypeOf(res.data) && Object.keys(res.data).length > 0) {
                                                    for (let i = 0; i < productList.length; i++) {
                                                        if (productList[i].type && productList[i].type == 'order') {
                                                            productList.splice(i, 1);
                                                        }
                                                    }
                                                    productList.push({
                                                        type: 'order',// 区分是带出来的还是自己添加的
                                                        id: res.data.id,
                                                        skuCode: res.data.skuCode,
                                                        skuSpecValueNames: res.data.skuSpecValueNames,
                                                        unitName: res.data.unitName,
                                                        weightNumber: res.data.weightNumber,
                                                        quantityStock: res.data.quantityStock,
                                                        shipmentQuantity: '',
                                                        remark: '',
                                                        status: 'no'
                                                    });

                                                } else {
                                                    for (let i = 0; i < productList.length; i++) {
                                                        if (productList[i].type && productList[i].type == 'order') {
                                                            productList.splice(i, 1);
                                                        }
                                                    }
                                                }
                                                // 渲染表格
                                                table.reload('storesRequisitionAddProductTable', {
                                                    data: productList,
                                                });

                                            }
                                        }, 'get');

                                        layer.close(selectTheWorkProcessTemplate);
                                    }
                                });
                            }
                        })
                    });

                    // 添加物料
                    $(".storesRequisitionAddProductBtn").click(function () {
                        if (cabinetId == '') {
                            layer.msg("请先选择柜子", {icon: 2});
                            return false;
                        }
                        var selectProductStockTemplate = admin.open({
                            type: 1,
                            title: '选择领新物料',
                            area: ['75%', '800px'],
                            offset: '85px',
                            content: $('#selectProductStockTemplate').html(),
                            success: function () {
                                form.render("select");
                                // 渲染表格
                                var selectProductStockTable = table.render({
                                    elem: '#selectProductStockTable',
                                    url: config.base + 'enterprisecab/cabinet/admin/storesRequisition/getProductDetailPageList?cabinetId=' + cabinetId,
                                    page: true,
                                    cellMinWidth: 100,
                                    cols: [[
                                        {type: 'radio'}
                                        , {field: 'skuCode', title: '物料编号', width: 200, align: 'center'}
                                        , {
                                            field: 'productPic',
                                            title: '图片',
                                            templet: (d) => "<img src='" + d.productPic + "' width='80px' height='80px'/>",
                                            align: 'center'
                                        }
                                        , {field: 'skuName', title: '物料名称', align: 'center'}
                                        , {field: 'oldSpecCode', title: '规格码', align: 'center'}
                                        , {field: 'packName', title: '包装规格', align: 'center'}
                                        , {field: 'unitName', title: '包装单位', align: 'center'}
                                        , {field: 'marketPrice', title: '单价', align: 'center'}
                                        , {field: 'quantityStock', title: '库存', align: 'center'}
                                    ]]
                                });

                                // 搜索
                                form.on('submit(selectProductStockFormSubSearchLog)', function (data) {
                                    selectProductStockTable.reload({
                                        where: data.field,
                                        page: {curr: 1}
                                    }, 'data');
                                });

                                // 确认选择
                                $('#selectProductStockClose').click(function () {
                                    let checkStatus = table.checkStatus('selectProductStockTable'); //test即为基础参数id对应的值
                                    let dataS = checkStatus.data[0];
                                    if (checkStatus.data.length == 0) {
                                        layer.msg("请选择领新物料", {icon: 2, time: 1000});
                                    } else {
                                        let filterList = productList.filter((item) => {
                                            return item.skuCode == dataS.skuCode
                                        });
                                        if (filterList.length > 0) {
                                            layer.msg('当前选择的物料已存在', {icon: 2});
                                            return false;
                                        }
                                        productList.push({
                                            type: 'add',// 区分是带出来的还是自己添加的
                                            id: dataS.id,
                                            skuCode: dataS.skuCode,
                                            skuName: dataS.skuName,
                                            skuSpecValueNames: dataS.skuSpecValueNames,
                                            oldSpecCode: dataS.oldSpecCode,
                                            unitName: dataS.unitName,
                                            weightNumber: dataS.weightNumber,
                                            quantityStock: dataS.quantityStock,
                                            shipmentQuantity: '',
                                            remark: '',
                                            status: 'no',
                                            packId: dataS.packId,
                                            packName: dataS.packName,
                                            baseRate: dataS.baseRate
                                        });
                                        // 渲染表格
                                        table.reload('storesRequisitionAddProductTable', {
                                            data: productList,
                                        });
                                        layer.close(selectProductStockTemplate);
                                    }
                                });
                            }
                        })
                    });
                    form.render('select');
                    // 渲染表格
                    var storesRequisitionAddProductTable = table.render({
                        elem: '#storesRequisitionAddProductTable',
                        data: productList,
                        cellMinWidth: 100,
                        cols: [[
                            {type: 'numbers', width: 50, title: '序号'}
                            , {field: 'skuName', title: '物料名称', align: 'center'}
                            , {field: 'skuCode', title: '物料编号', align: 'center'}
                            , {field: 'oldSpecCode', title: '规格码', align: 'center'}
                            , {field: 'unitName', title: '包装单位', align: 'center'}
                            , {field: 'quantityStock', title: '当前库存', align: 'center'}
                            , {field: 'packId', title: '包装规格ID', align: 'center', hide: "true"}
                            , {field: 'baseRate', title: '换算率', align: 'center', hide: "true"}
                            , {field: 'packName', title: '包装规格', align: 'center'}
                            /*, {
                                field: 'packId', title: '包装规格', width: 170,
                                templet: function (d) {
                                    if (d.status == 'yes') {
                                        return '<span style="height: 32px;">' + d.packName + '</span>'
                                    } else {
                                        let selectHtml = '<select  lay-verify="required" class="packSelect" name="packId"><option value="">请选择包装规格</option>';
                                        packData.forEach(item => {
                                            if (item.id === d.packId) {
                                                selectHtml += `<option selected value="${item.id}" data='${JSON.stringify(item)}'>${item.name}</option>`
                                            } else {
                                                selectHtml += `<option value="${item.id}" data='${JSON.stringify(item)}'>${item.name}</option>`
                                            }
                                        });
                                        selectHtml += '</select>';
                                        return selectHtml
                                    }
                                }
                            }*/
                            , {
                                field: 'shipmentQuantity',
                                title: '出货数量',
                                align: 'center',
                                width: 170,
                                templet: function (d) {
                                    if (d.status == 'yes') {
                                        return '<span style="height: 32px;">' + d.shipmentQuantity + '</span>'
                                    } else {
                                        return '<input productId="' + d.id + '" class="layui-input shipmentQuantity" style="height: 32px;" type="text" ' +
                                            'value="' + d.shipmentQuantity + '" lay-verify="required"/>'
                                    }
                                }
                            }
                            , {
                                field: 'remark',
                                title: '备注说明',
                                align: 'center',
                                width: 270,
                                templet: function (d) {
                                    if (d.status == 'yes') {
                                        return '<span style="height: 32px;">' + d.remark + '</span>'
                                    } else {
                                        return '<input productId="' + d.id + '" class="layui-input remark" style="height: 32px;" type="text" ' +
                                            'value="' + d.remark + '"/>'
                                    }
                                }
                            }
                            , {
                                align: 'center',
                                toolbar: '#storesRequisitionAddProductTableBar',
                                title: '操作',
                                width: 120
                            }
                        ]],
                    });

                    // 出货数量
                    $("body").delegate(".shipmentQuantity", "change", function () {
                        let id = $(this).attr('productId');
                        let reg = /^[1-9]+[0-9]*$/;
                        let quantity = $(this).val();
                        productList.forEach(item => {
                            if ((item.id === id)) {
                                let quantityStock = parseInt(item.quantityStock);
                                if (!reg.test(quantity)) {
                                    layer.msg('请输入正确的数字', {icon: 2});
                                    $(this).val('');
                                }
                                /*if (parseInt(quantity) > quantityStock) {
                                    layer.msg('出货数量不能大于当前物料库存数', {icon: 2});
                                    $(this).val(quantityStock);
                                    return false;
                                }*/
                            }
                        })
                    });

                    //包装规格


                    form.on("select", function (data) {
                        if ($(data.elem).attr('name') == 'packId') {
                            if (data.value != '') {
                                let _data = JSON.parse($(data.elem[data.elem.selectedIndex]).attr('data'));
                                productList[$(data.elem).parents('tr').index()].packId = data.value;
                                productList[$(data.elem).parents('tr').index()].packName = _data.name;
                                productList[$(data.elem).parents('tr').index()].baseRate = _data.baseRate
                            } else {
                                productList[$(data.elem).parents('tr').index()].packId = '';
                                productList[$(data.elem).parents('tr').index()].packName = '';
                                productList[$(data.elem).parents('tr').index()].baseRate = ''
                            }
                        }
                    });

                    table.on("tool(storesRequisitionAddProductTable)", function (obj) {
                        let rowData = obj.data;
                        if (obj.event === 'save') { // 保存
                            let shipmentQuantity = $(this).parents('td').siblings().find('.shipmentQuantity').val();
                            let remark = $(this).parents('td').siblings().find('.remark').val();

                            if (productList[$(this).parents('tr').index()].packId === '') {
                                layer.msg('请选择包装规格', {icon: 2});
                                return false;
                            }

                            if (shipmentQuantity == '') {
                                layer.msg('请输入出库数量', {icon: 2});
                                return false;
                            }

                            if (shipmentQuantity == 0) {
                                return false;
                            }
                            productList.forEach(item => {
                                if ((rowData.id === item.id)) {
                                    item.status = 'yes';
                                    item.shipmentQuantity = shipmentQuantity;
                                    item.remark = remark;
                                }
                            });
                        } else if (obj.event === 'del') { //删除
                            productList.forEach((item, index) => {
                                if ((rowData.id === item.id)) {
                                    productList.splice(index, 1)
                                }
                            });
                        } else if (obj.event === 'edit') { //修改
                            productList.forEach(item => {
                                if ((rowData.id === item.id)) {
                                    item.status = 'no';
                                }
                            });
                        }
                        // 渲染表格
                        table.reload('storesRequisitionAddProductTable', {
                            data: productList,
                        });
                    });

                    // 表单提交
                    form.on('submit(storesRequisitionAddFormSubmit)', function (d) {
                        let list = [];
                        if (productList.length == 0) {
                            layer.msg('请添加领新物料', {icon: 2});
                            return false;
                        }
                        // 筛选出有保存过的物料
                        let productFilter = productList.filter(item => {
                            return item.status == 'yes'
                        });
                        if (productFilter.length == 0) {
                            layer.msg('请保存领新物料', {icon: 2});
                            return false;
                        }

                        productFilter.forEach(ele => {
                            list.push({
                                remark: ele.remark,
                                skuCode: ele.skuCode,
                                shipmentQuantity: ele.shipmentQuantity,
                                packId: ele.packId,
                                baseRate: ele.baseRate,
                            })
                        });
                        let params = {
                            cabinetId: cabinetId,
                            cabinetCode: cabinetCode,
                            processId: processId,
                            workOrderId: workOrderId,
                            simpleWorkOrderId: workOrderId,
                            userId: d.field.userId,
                            productDetail: list,
                            workOrderWay
                        };
                        if (workOrderWay == 'mes') {
                            params.workOrderId = workOrderId;
                            delete params.simpleWorkOrderId;
                        } else if (workOrderWay == 'simple') {
                            delete params.workOrderId;
                            params.simpleWorkOrderId = workOrderId;
                        }

                        layer.load(2);
                        admin.req('enterprisecab/cabinet/admin/storesRequisition/submitStoresRequisition', JSON.stringify(params), function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('storesRequisitionTable');
                                layer.closeAll();
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'POST', true, 'application/json; charset=utf-8');
                        return false;
                    });
                }
            });
        }

        // 显示详情弹窗
        function storesRequisitionDetailModel(data, type) {
            admin.open({
                type: 1,
                area: ['85%', '820px'],
                offset: '65px',
                title: type === 'check' ? '审核领新申请' : '领新申请详情',
                content: $('#storesRequisitionDetailTemplate').html(),
                success: function () {
                    let storesRequisitionList = [];
                    let isHide = true;

                    // 如果是发送短信
                    if (type == 'send') {
                        isHide = false
                    }
                    // 渲染表格
                    var storesRequisitionTopTable = table.render({
                        elem: '#storesRequisitionTopTable',
                        data: [data],
                        cellMinWidth: 100,
                        cols: [[
                            {field: 'cabinetCode', title: '出货货柜', align: 'center'}
                            // , {field: 'processName', title: '所属工序', align: 'center'}
                            // , {field: 'workOrderCode', title: '所属工单', align: 'center'}
                            , {field: 'creatorName', title: '领取人', align: 'center'}
                            , {field: 'phone', title: '领取人电话', align: 'center'}
                            , {field: 'departmentName', title: '所属部门', align: 'center'}
                            , {field: 'roleName', title: '所属岗位', align: 'center'}
                            , {field: 'lnstructionCode', title: '指令密码', align: 'center', hide: isHide}
                            , {
                                align: 'center',
                                toolbar: '#storesRequisitionTopTableBar',
                                title: '操作',
                                hide: isHide
                            }
                        ]],
                    });

                    // 表格操作
                    table.on("tool(storesRequisitionTopTable)", function (obj) {
                        if (obj.event === 'send') { // 发送
                            sendCode(data.id);
                        }
                    });

                    // 发送短信通知
                    function sendCode(id) {
                        layer.confirm('确定发送短信通知吗？', {
                            skin: 'layui-layer-admin'
                        }, function (i) {
                            layer.close(i);
                            layer.load(2);
                            admin.req('enterprisecab/cabinet/admin/storesRequisition/sendInstruct', {
                                storesRequisitionId: id
                            }, function (data) {
                                layer.closeAll('loading');
                                if (data.code == 200) {
                                    layer.msg(data.msg, {icon: 1});
                                } else {
                                    layer.msg(data.msg, {icon: 2});
                                }
                            }, 'GET');
                        });
                    }

                    // 获取领新物料表
                    admin.reqSync('enterprisecab/cabinet/admin/storesRequisition/storesRequisitionProductPageList', {
                        storesRequisitionId: data.id
                    }, function (res) {
                        if (res.code == 200) {
                            storesRequisitionList = res.data;
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }, 'GET');

                    form.render('select');

                    // 如果是审核则显示提交按钮 如果是已审核则显示对应状态
                    if (type == 'check') {
                        $(".isCheckStatus").show();
                    } else {
                        $('#checkStatus').attr('disabled', 'disabled');
                        if (data.status == 'checked') {
                            let select = 'dd[lay-value=' + data.checkStatus + ']';
                            $('#checkStatus').siblings("div.layui-form-select").find('dl').find(select).click();
                        }
                        form.render('select');
                        $(".isCheckStatus").hide();
                    }

                    var storesRequisitionTopTable = table.render({
                        elem: '#storesRequisitionBottomTable',
                        data: storesRequisitionList,
                        cellMinWidth: 100,
                        cols: [[
                            {type: 'numbers', width: 50, title: '序号'}
                            , {field: 'skuName', title: '物料名称', align: 'center'}
                            , {field: 'skuCode', title: '物料编号', align: 'center'}
                            , {field: 'oldSpecCode', title: '规格码', align: 'center'}
                            , {field: 'unitName', title: '单位', align: 'center'}
                            , {field: 'inventory', title: '当前库存', align: 'center'}
                            , {field: 'shipmentQuantity', title: '出货数量', align: 'center'}
                            , {field: 'remark', title: '备注说明', align: 'center'}
                        ]],
                    });

                    // 提交审核
                    form.on('submit(storesRequisitionDetailFormSubmit)', function (d) {
                        layer.load(2);
                        admin.req('enterprisecab/cabinet/admin/storesRequisition/update', {
                            status: 'checked',
                            checkStatus: d.field.checkStatus,
                            id: data.id
                        }, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('storesRequisitionTable');
                                layer.closeAll();
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'PUT');
                        return false;
                    });
                }
            })
        }

        // option渲染
        function loadSelectHtml(data, tips, htmltarget, type) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type === 1) {
                    html += `<option value='${data[i].id}'>${data[i].cabCode}</option>`;
                } else if (type === 2) {
                    html += `<option value='${data[i].id}'>${data[i].nickname}</option>`;
                }
            }

            $("form select[name='" + htmltarget + "']").html(html);
            form.render('select');
        }

    });
</script>